package com.chj.setmsg;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeoutException;

/**
 * 消息的属性的控制
 */
public class ReplyToProducer {
    public final static String EXCHANGE_NAME = "replyto";
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("10.200.169.5");
        connectionFactory.setVirtualHost("chj_vhost");
        connectionFactory.setUsername("chj");
        connectionFactory.setPassword("123456");
        // 创建连接
        Connection connection = connectionFactory.newConnection();
        final Channel channel = connection.createChannel();
        // 创建交换器 BuiltinExchangeType.DIRECT == direct
        channel.exchangeDeclare(ReplyToProducer.EXCHANGE_NAME, "direct", false);
        //TODO 响应QueueName ，消费者将会把要返回的信息发送到该Queue
        String responseQueue = channel.queueDeclare().getQueue();
        //TODO 消息的唯一id
        String msgId = UUID.randomUUID().toString();
        AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder()
                .replyTo(responseQueue)
                .messageId(msgId).build();
        //日志消息级别，作为路由键使用
        String routekey = "error";
        // 声明了一个消费者
        final Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag,Envelope envelope,
                                       AMQP.BasicProperties properties,
                                       byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                // envelope.getRoutingKey() = properties.getReplyTo() 因为消费者将路由键设置为respProp.getReplyTo()
                System.out.println("Producer Received["+envelope.getRoutingKey() +"]"+message);
            }
        };
        //TODO 消费者应答队列上的消息
        channel.basicConsume(responseQueue,true,consumer);
        String msg = "Hello,RabbitMq";
        //TODO 发送消息时，把响应相关属性设置进去
        channel.basicPublish(EXCHANGE_NAME,routekey,properties,msg.getBytes());
        System.out.println("Sent error:"+msg);
    }
}
